package com.ama.ticket;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.persistence.*;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    @Override
    protected void doGet(
        HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 


        // Obtain a database connection:
        EntityManagerFactory emf =
           (EntityManagerFactory)getServletContext().getAttribute("emf");
        EntityManager em = emf.createEntityManager();

    	if (request.getParameterMap().containsKey("op")) {
    		String op = request.getParameter("op");
    		System.out.println("User:"+request.getParameter("id"));
    		Long id = Long.valueOf(request.getParameter("id"));
    		try {
	    		em.getTransaction().begin();
	    		
	            User user = em.find(User.class,id);
	            System.out.println("User:"+user);
	            em.remove(user);
	            em.getTransaction().commit();
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	
        try {
            // Handle a new guest (if any):
            String name = request.getParameter("name");
            if (name != null) {
                em.getTransaction().begin();
                em.persist(new User(name));
                em.getTransaction().commit();
            }
 
            // Display the list of guests:
            List<User> userList = em.createQuery(
                "SELECT g FROM User g", User.class).getResultList();
            List<Ticket> ticketList = em.createQuery(
                    "SELECT g FROM Ticket g", Ticket.class).getResultList();
            request.setAttribute("users", userList);
            request.setAttribute("tickets", ticketList);
            request.getRequestDispatcher("/user.jsp")
                .forward(request, response);
 
        } finally {
            // Close the database connection:
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            em.close();
        }
    }
 
    @Override
    protected void doPost(
        HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
